package com.yaorange.springsecuirtydemo.filter;

import com.yaorange.springsecuirtydemo.domain.LoginUser;
import com.yaorange.springsecuirtydemo.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;


/**
 * token过滤器 验证token有效性
 * @author coach tam
 * @email 327395128@qq.com
 * @values 坚持灵活 灵活坚持
 * @since 2024/5/28
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    public JwtAuthenticationTokenFilter() {
        System.out.println("JwtAuthenticationTokenFilter init");
    }

    @Autowired
    private TokenService tokenService;
    //白名单
    private List<String> whiteList = Arrays.asList("/login", "/logout", "/hello");

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        //如果是白名单，直接放行
        if (whiteList.contains(request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }

        try {
            //根据请求信息中的token获取到对应的用户信息
            LoginUser loginUser = tokenService.getLoginUser(request);
            //将用户信息放入到Security上下文中
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(loginUser);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            chain.doFilter(request, response);
        } catch (Exception e) {
            response.setStatus(401);
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().write("{\"code\":401,\"msg\":\"token无效\"}");
        }
    }
}
